package com.jlz.actions.register;

import org.apache.commons.lang.StringUtils;
import org.apache.struts2.convention.annotation.Standard;
import org.springframework.beans.factory.annotation.Autowired;

import com.jlz.beans.user.LinkBean;
import com.jlz.beans.user.UserBean;
import com.jlz.managers.def.Sites;
import com.jlz.managers.user.Links;
import com.jlz.managers.user.Users;
import com.jlz.service.email.EmailService;
import com.julewa.Client;
import com.julewa.db.BeanValidator;
import com.julewa.utils.Patterns;

@Standard
public class StartAction {
	@Autowired Client client;
	@Autowired Users users;
	@Autowired Links links;
	@Autowired EmailService emailsrv;
	private @Autowired BeanValidator validator;
	
	private String usercode=null;
	private String username=null;
	private String password=null; 
	private String repassword = null;
	
	//只支持邮件,因为支持短信代价太大.
	//因为有139 wo这样的运营商免费短信提醒邮箱
	//则直接支持短信的紧迫性就不需要乐
	public String execute(){
		//
		usercode = StringUtils.trimToNull(usercode);
		if(validator.checkField("usercode", "账号", usercode, 3, 100) && usercode.indexOf('@') >= 0){
			if(!Patterns.EMAIL.match(usercode)){
				client.setError("usercode", "您设的邮箱名格式错误");
			}
		}
		//
		username = StringUtils.trimToNull(username);
		validator.checkField("username", "别名", username, 2, 100);
		//
		password = StringUtils.trimToEmpty(password);
		if(validator.checkField("password", "密码", password, 6, 60)){
			if(!password.equals(repassword)){
				client.setError("repassword", "确认密码不一致");
			}
		}
		if(client.hasError()){
			return "index";
		}
		//
		LinkBean link = links.find(usercode);
		if(link.getUserId() != null){
			client.setError("usercode", "账号已存在,请选择另外的账号");
			return "index";
		}
		UserBean user = new UserBean();
		user.setName(username);
		users.append(user);
		link.setUserId(user.getID());
		link.setPassword(password);
		link.setState(Links.State.NEW.getValue());
		links.append(link);
		//
		if(link.getSiteId() < Sites.SITES){
			client.setUser(user);
			return "active";
		}else{
			emailsrv.sendRegisterNotice(usercode, username, 
					links.encode(link));
			return "notice";
		}
	}
	
	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public void setRepassword(String repassword) {
		this.repassword = repassword;
	}

	public String getRepassword() {
		return repassword;
	}

	public String getUsercode() {
		return usercode;
	}

	public void setUsercode(String usercode) {
		this.usercode = usercode;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

}
